package middleware

import (
	"context"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func ContextTimeout(timeout time.Duration) func(c *gin.Context) {
	return func(c *gin.Context) {
		ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
		defer cancel()
		c.Request = c.Request.WithContext(ctx)

		response := make(chan struct{}, 1)
		go func() {
			c.Next()
			response <- struct{}{}
		}()
		select {
		case <-response:
			return
		case <-ctx.Done():
			if ctx.Err() == context.DeadlineExceeded {
				c.JSON(http.StatusOK, gin.H{"message": "Request timeout"})
			}
			c.Abort()
			return
		}
	}
}
